<template>
  <div>
    <div id="app" class="parent-container">
      <div class="text">姓名：{{ loginName }}</div>
      <div class="text">年龄：{{ loginAge }}</div>
      <div class="media">
        <video
          class="video"
          width="500"
          height="375"
          ref="video"
          :srcObject.prop="videoSource"
          autoplay
        >
          Video stream not available.
        </video>

        <img
          class="image"
          width="500"
          height="375"
          :src="photoSource"
          alt="The screen capture will appear in this box."
        />
      </div>
      <div>
        <el-row> </el-row>
      </div>
      <div>
        <el-button :type="lefttype" @click="takepictureleft" plain>左眼</el-button>
        <el-button :type="righttype" @click="takepictureright" plain>右眼</el-button>
        
      </div>
      <div>
        <el-button @click="autoFocus" plain>自动对焦</el-button> 
        <el-slider v-model="brightness" @input="adjustBrightness" :min="0" :max="100" />
      </div>
      <canvas width="500" height="375" ref="canvas" id="canvas" />
    </div>
  </div>
</template>
  
  <script>
  import axios from 'axios'



  export default {
    name: "Image",
    data() {
      return {
        loginAge:'',
        loginName:'',
        showname: false,
        videoSource: null,
        photoSource: null,
        videoDevices: null,
        audioDevices: null,
        selectedCamera: null,
        selectedMic: null,
        lefttype: "primary",
        righttype: "primary",
        barcodetype: "primary",
        maninfovisible: false,
        brightness: 50, // 初始亮度
      };
    },
    methods: {
      async takepictureleft() {
        let context = this.$refs.canvas.getContext("2d");
        // 绘制图片
        context.drawImage(this.$refs.video, 0, 0, 500, 375);
        // 将canvas转换为图片
        this.$refs.canvas.toBlob(async (blob) => {
          const formData = new FormData();
          formData.append('image', blob, 'left.png');

          try {
            const res = await axios.post("https://" + this.URLhost + "/smallProgramTest/upload", formData, {
              headers: {
                'Content-Type': 'multipart/form-data'
              }
            });

            console.log(res);
            const { code, msg } = res.data;
            if (code === 1) {
              this.$message({
                message: msg,
                type: "success",
              });
            } else if (code === 2 || code === 0) {
              this.lefttype = "success";
              this.$message({
                type: "success",
                message: msg,
              });
            } else {
              this.$message({
                type: "warning",
                message: msg,
              });
              this.lefttype = "warning";
            }
          } catch (error) {
            console.error("Error uploading image:", error);
            this.$message({
              type: "error",
              message: "上传失败，请重试。",
            });
          }

        }, 'image/png');
      },
      takepictureright() {
        let context = this.$refs.canvas.getContext("2d");
        // 绘制图片
        context.drawImage(this.$refs.video, 0, 0, 500, 375);
        // 将canvas转换为图片
        this.$refs.canvas.toBlob(async (blob) => {
          const formData = new FormData();
          formData.append('image', blob, 'right.png');

          try {
            const res = await axios.post("https://" + this.URLhost + "/smallProgramTest/upload", formData, {
              headers: {
                'Content-Type': 'multipart/form-data'
              }
            });

            console.log(res);
            const { code, msg } = res.data;
            if (code === 1) {
              this.$message({
                message: msg,
                type: "success",
              });
            } else if (code === 2 || code === 0) {
              this.lefttype = "success";
              this.$message({
                type: "success",
                message: msg,
              });
            } else {
              this.$message({
                type: "warning",
                message: msg,
              });
              this.lefttype = "warning";
            }
          } catch (error) {
            console.error("Error uploading image:", error);
            this.$message({
              type: "error",
              message: "上传失败，请重试。",
            });
          }

        }, 'image/png');
      },
      startup() {
        navigator.mediaDevices
          .getUserMedia({ video: true, audio: false })
          .then((stream) => {
            this.videoSource = stream;
          })
          .catch((err) => {
            console.log("An error occurred: " + err);
          });
  
        this.clearPhoto();
      },
      clearPhoto() {
        const context = this.$refs.canvas.getContext("2d");
        context.fillStyle = "#AAA";
        context.fillRect(0, 0, 500, 375);
  
        const data = this.$refs.canvas.toDataURL("image/png");
        this.photoSource = data;
        console.log("拍照初始化")
      },
      async getConnectedDevices() {
        await navigator.mediaDevices.enumerateDevices().then((devices) => {
          // 过滤出视频设备
          this.videoDevices = devices.filter(
            (device) => device.kind === "videoinput"
          );
          // 过滤出音频设备
          this.audioDevices = devices.filter(
            (device) => device.kind === "audioinput"
          );
        });
        // 选择初始设备
        this.selectInitialDevices();
      },
      selectInitialDevices() {
        this.selectedCamera = this.videoDevices[0].deviceId;
        this.selectedMic = this.audioDevices[0].deviceId;
      },
      autoFocus() {
        const track = this.videoSource.getVideoTracks()[0];
        const capabilities = track.getCapabilities();
        
        if (capabilities.focusMode) {
          track.applyConstraints({
            advanced: [{ focusMode: "continuous" }]
          });
          this.$message({
            type: "success",
            message: "自动对焦已启用",
          });
        } else {
          this.$message({
            type: "warning",
            message: "该设备不支持自动对焦",
          });
        }
      },
      adjustBrightness(value) {
        const videoElement = this.$refs.video;
        videoElement.style.filter = `brightness(${value}%)`;
      }
    },
    mounted() {
      this.startup();
      this.getConnectedDevices();
    //   this.reshot();
    },
  };
  </script>
  
  <style>
  * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }
  
  #app {
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    /* min-height: 100vh; */
    /* padding: 2rem; */
    display: flex;
    flex-direction: column;
    gap: 1rem;
  }
  .text {  
    text-align: left;
    font-weight: bold;  
    font-size: 1.5em;
    }
  
  .media {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 3rem;
  }
  
  #canvas {
    display: none;
  }
  
  .video {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 2rem;
    align-items: center;
    border-radius: 8px;
    overflow: hidden;
  }
  
  .image {
    border-radius: 8px;
    overflow: hidden;
  }
  
  label {
    font-weight: 800;
  }
  
  select {
    height: 2rem;
  }
  
  .el-button--custom {
    font-size: 3rem;
    height: 80px;
    width: 100px;
  }
  
  .parent-container {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .el-slider {
    width: 400px;
    margin-top: 20px;
  }
  </style>
  